package com.etc.service;

import com.etc.common.MyServiceException;
import com.etc.dao.CarMapper;
import com.etc.pojo.CarMstPojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Service
public class CarService {

    private final CarMapper carMapper;
    @Value("${file.upload}")
    String path;

    public CarService(CarMapper carMapper) {
        this.carMapper = carMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public void addCar(CarMstPojo carMstPojo) {


        // 做处理 base64-->file
        String fileName = UUID.randomUUID().toString();
        String filePath = path  + "/" + fileName;


        byte[] bs = Base64.getDecoder().decode(carMstPojo.getImage());
        try {
            Files.write(Paths.get(filePath), bs, StandardOpenOption.CREATE);
        } catch (IOException e) {
            throw new MyServiceException("文件写入失败请联系管理员！", e);
        }
        carMstPojo.setImage(fileName);

        int r = carMapper.insert(carMstPojo);
        if (r != 1) {

            throw new MyServiceException("请联系管理员！");
        }
    }

    public List<CarMstPojo> findByCondition(CarMstPojo pojo) {

        List<CarMstPojo> clist = carMapper.selectByCondition(pojo);

        if (clist.size() == 0) {
            throw new MyServiceException("0条记录");
        }
        return clist;
    }
}
